import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    component: () => import("@/views/FrontLayout.vue"),
    children: [
      {
        path: "",
        name: "Home",
        component: () => import("@/views/HomePage.vue"),
        meta: { title: "首页" },
      },
      {
        path: "pet/list",
        name: "PetList",
        component: () => import("@/views/PetList.vue"),
        meta: { title: "宠物列表" },
      },
      {
        path: "pet/detail/:id",
        name: "PetDetail",
        component: () => import("@/views/PetDetail.vue"),
        meta: { title: "宠物详情" },
        props: true,
      },
      {
        path: "pet/adoption",
        name: "PetAdoption",
        component: () => import("@/views/PetList.vue"),
        meta: { title: "待领养宠物" },
        props: { status: "1" },
      },
      {
        path: "about",
        name: "About",
        component: () => import("@/views/AboutUs.vue"),
        meta: { title: "关于我们" },
      },
      {
        path: "user",
        meta: { requireAuth: true },
        children: [
          {
            path: "profile",
            name: "UserProfile",
            component: () => import("@/views/user/Profile.vue"),
            meta: { title: "个人中心", requireAuth: true },
          },
          {
            path: "adoptions",
            name: "UserAdoptions",
            component: () => import("@/views/user/Adoptions.vue"),
            meta: { title: "我的领养", requireAuth: true },
          },
          {
            path: "comments",
            name: "UserComments",
            component: () => import("@/views/user/Comments.vue"),
            meta: { title: "我的评论", requireAuth: true },
          },
        ],
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue"),
    meta: { title: "登录" },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/Register.vue"),
    meta: { title: "注册" },
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/NotFound.vue"),
    meta: { title: "页面不存在" },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局前置守卫，用于验证用户是否登录
router.beforeEach((to, from, next) => {
  // 修改页面标题
  document.title = to.meta.title ? `${to.meta.title} - 爪印` : "爪印";

  // 判断是否需要登录权限
  if (to.matched.some((record) => record.meta.requireAuth)) {
    // 这里应该判断用户是否已登录
    // 这里使用模拟登录状态，实际开发中应该从localStorage、cookie或vuex中获取
    const isLogin = localStorage.getItem("isLogin") === "true";

    if (isLogin) {
      next();
    } else {
      next({
        path: "/login",
        query: { redirect: to.fullPath }, // 登录成功后重定向到原来的页面
      });
    }
  } else {
    next();
  }
});

export default router;
